package com.et.util

import java.io.BufferedReader
import java.io.DataOutputStream
import java.io.InputStreamReader

fun shell(shell: String, string: StringBuilder, root: Boolean = true): Boolean? {
    var b: Boolean? = null
    Runtime.getRuntime().apply {
        val process = exec(if (root) "su" else "sh")
        DataOutputStream(process.outputStream).apply {
            writeBytes(shell)
            writeBytes("\n")
            writeBytes("exit\n")
            flush()
            process.waitFor()
        }

        InputStreamReader(process.inputStream).use { read ->
            BufferedReader(read).use { reader ->
                reader.readLines().let { it ->
                    if (it.isNotEmpty()) {
                        b = true
                        it.forEach {
                            string.append(it).append('&')
                        }
                    }
                }
            }
        }

        InputStreamReader(process.errorStream).use { read ->
            BufferedReader(read).use { reader ->
                reader.readLines().let {
                    if (it.isNotEmpty()) {
                        b = false
                        it.forEach {
                            string.append(it)
                        }
                    }
                }
            }
        }
    }
    return b
}